use crate::config::api::R;
use crate::middleware::auth_middleware::Authenticate;
use crate::models::student::Student;
use actix_web::{get, post, web, HttpResponse, Responder};
use actix_web::web::Json;
use rbatis::RBatis;
pub fn init(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/student")
            .wrap(Authenticate)
            .service(get_student_list)
            .service(insert_student)
    );
}

#[get("/list")]
async fn get_student_list(rb: web::Data<RBatis>) -> impl Responder {
    let res = Student::select_all(rb.get_ref()).await;
    match res {
        Ok(all) => {
            let res = Json(R::ok(all));
            HttpResponse::Ok().json(res)
        }
        Err(e) => {
            println!("{}", e);
            let res: Json<R<String>> = Json(R::error(400, &e.to_string()));
            HttpResponse::InternalServerError().json(res)
        }
    }
}

#[post("/add")]
async fn insert_student(student: Json<Student>, rb: web::Data<RBatis>) -> impl Responder {
    log::info!("接收到添加学生请求:{:?}", student);
    let result = Student::insert(rb.get_ref(), &student).await;
    match result {
        Ok(_) => {
            let res: Json<R<String>> = Json(R::ok_none());
            HttpResponse::Ok().json(res)
        }
        Err(e) => {
            println!("{}", e);
            let res: Json<R<String>> = Json(R::error(400, &String::from(e.to_string())));
            HttpResponse::Ok().json(res)
        }
    }
}
